<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="领用列表"
      :columns="columns"
      :request="fetchReceivePage"
    >
      <template #operation>
        <n-space>
          <n-button type="primary" @click="handleAddReceive">新增领用</n-button>
        </n-space>
      </template>
    </pro-table>

    <pro-dialog
      v-model:showDialog="receiveModalShow"
      :modalProps="modalProps"
      :width="1000"
      :showButton="true"
      :showConfirmButton="handleType !== 'check'"
      :cancelButtonText="handleType === 'check' ? '关闭' : '取消'"
      :contentStyle="{ 'padding-left': '10px', 'padding-right': '10px' }"
      :button-loading="confirmLoading"
      @handleConfirm="receiveConfirm"
      @afterClosed="resetReceiveForm"
      v-bind="$attrs"
    >
      <pro-form
        ref="receiveFormInst"
        v-model:form="receiveForm"
        :formProps="{
          labelPlacement: 'left',
          labelWidth: '100px'
        }"
        :options="receiveFormOptions"
      ></pro-form>
    </pro-dialog>
  </div>
</template>

<script lang="ts" setup name="Receive">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import { useReceiveApi, useReceiveProForm, useReceiveProTable } from './hooks'
  import { ReceiveModel } from '@/api/model/workflow/receive-model'
  import getUserInfo from '@/hooks/getUserInfo'

  const proTableInst = ref<ProTableInst | null>(null)
  const receiveFormInst = ref<ProFormInst | null>(null)

  const { userInfo } = getUserInfo()

  const receiveModalShow = ref(false)
  const handleType = ref<'add' | 'edit' | 'check'>('check')
  const handleTag = computed(() =>
    handleType.value === 'add'
      ? '新增领用'
      : handleType.value === 'check'
      ? '领用详情'
      : '修改领用'
  )
  const modalProps = computed(() => {
    return {
      showIcon: false,
      title: handleTag.value
    }
  })
  const { receiveForm, resetReceiveForm, receiveFormOptions } =
    useReceiveProForm({ handleType })

  const handleAddReceive = () => {
    handleType.value = 'add'
    receiveModalShow.value = true
  }

  const handleEditReceive = (row: ReceiveModel, type: 'check' | 'edit') => {
    receiveForm.value = row
    handleType.value = type
    receiveModalShow.value = true
  }

  const receiveConfirm = async () => {
    if (await receiveFormInst.value?.handleSubmit()) {
      fetchAddOrEditReceive()
    }
  }

  const {
    fetchReceivePage,
    fetchAddOrEditReceive,
    fetchDelReceive,
    confirmLoading
  } = useReceiveApi({
    handleType,
    handleTag,
    receiveModalShow,
    receiveForm,
    proTableInst,
    userInfo
  })
  const { columns } = useReceiveProTable({
    handleEditReceive,
    fetchDelReceive
  })
</script>

<style lang="less" scoped></style>
